<?php
require_once 'lib/controllerWithoutGetOrPost.php';
/**
 * Check if the user id is encrypted within the authentication code
 *
 * @return bool
 * @param int $userId
 * @param string $authCode
 */
function isValidCode($userId, $authCode)
{
    // See: http://www.php.net/crypt#function.crypt.examples
    
    $isValid = (crypt((string)$userId, $authCode) === $authCode);
    return $isValid;
}
/**
 * Check if the authentication time is older than one day
 *
 * @return bool
 * @param int $userId
 */
function isUnexpiredTime($userId)
{
    global $db;
    $sql = <<< EOT
        SELECT Time
        FROM Authentication, Users
        WHERE
            Authentication.ID = Users.AuthID AND
            Users.ID = %d
          
EOT;
    $sql = sprintf($sql,
        $userId
    );
    $result = $db->query($sql);
    if ($db->rowCount($result) > 0) {
        $row = $db->fetch($result);
        $value = $db->unescape($row['Time']);
    }
    $authTime = mktime($value);
    $nowTime = strtotime('now');
    $oneDay = 24 * 60 * 60;
    $oneWeek = $oneDay * 7;
    $isUnexpired = $nowTime - $oneWeek < $authTime;
    return $isUnexpired;
}
/**
 * Enable the users account
 *
 * @return void
 * @param int $userId
 */
function enableUser($userId)
{
    global $db;
    $sql = <<< EOT
        UPDATE Users
        SET Enable = 1,
        WHERE ID = %d
EOT;
    $sql = sprintf($sql, $userId);
    $db->query($sql);
}
/**
 * Show the success activation message
 *
 * @return string
 */
function activationSuccess()
{
    return 'Thankyou, Your account is now activated<br /><a href="http://www.amemorytree.co.nz/member.php">Log In</a>';
}
/**
 * Show the failed activation message
 *
 * @return string
 */
function activationFailed()
{
    return 'Activation failed.<br /><a href="http://www.amemorytree.co.nz/">A Memory Tree</a>';
}
$userId = intval($_GET['userid']);
$authCode = $db->escape($_GET['auth']);
$isValidAuthentication = FALSE;
if (!empty($userId) && !empty($authCode)) {
    $isValidAuthentication = isValidCode($userId, $authCode) && isUnexpiredTime($userId);
    if ($isValidAuthentication) {
        enableUser($userId);
    }
}
/*
if ($isValidAuthentication === TRUE) {
    echo activationSuccess();
} else {
    echo activationFailed();
}
*/
?>
